package cn.nebula.music.service;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.nebula.music.dao.RoleDAO;
import cn.nebula.music.dao.UserDAO;
import cn.nebula.music.domain.Role;
import cn.nebula.music.domain.User;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDAO roleDAO;

	@Autowired
	private UserDAO userDAO;

	@Override
	public Set<Role> findAllRoles() throws Exception {
		return roleDAO.findAllRoles();
	}

	@Override
	public Set<Role> findAllRolesOfBT() throws Exception {
		return roleDAO.findAllRolesOfBT();
	}

	@Override
	public Role findRoleById(Integer id) throws Exception {
		return roleDAO.findRoleById(id);
	}

	@Override
	public Role findRoleByName(String name) throws Exception {
		return roleDAO.findRoleByName(name);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void addRole(Role role) throws Exception {
		roleDAO.addRole(role);
		Set<User> users = role.getUsers();
		if (users != null) {
			for (User user : users) {
				User user1 = userDAO.findUserById(user.getId());
				user1.setRole(role);
				userDAO.updateUser(user1);
			}
		}
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateRole(Role role) throws Exception {
		roleDAO.updateRole(role);
		Boolean isModify = false;
		int size1 = 0;// 更改前的数量
		int size2 = 0;// 更改后的数量
		Set<User> users1 = findRoleById(role.getId()).getUsers();
		Set<User> users2 = role.getUsers();
		if (users1 != null) {
			size1 = users1.size();
		}
		if (users2 != null) {
			size2 = users2.size();
		}
		if (size1 == size2) {
			if (!users1.toString().equals(users2.toString())) {
				isModify = true;
			}
		} else {
			isModify = true;
		}
		if (isModify == true) {
			for (User user : users1) {
				user.setRole(null);
				userDAO.updateUser(user);
			}
			for (User user : users2) {
				user.setRole(role);
				userDAO.updateUser(user);
			}
		}
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void deleteRoleById(Integer id) throws Exception {
		for (User user : userDAO.findAllUsers()) {
			if (user.getRole() != null && user.getRole().getId().equals(id)) {
				user.setRole(null);
				userDAO.updateUser(user);
			}
		}
		roleDAO.deleteRoleById(id);

	}

}
